package cn.wolfcode.p2p.base.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.service.ILoginInfoService;

public class DBRealm extends AuthorizingRealm {

    @Autowired
    private ILoginInfoService loginInfoService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取令牌中的用户名
        String username = (String) token.getPrincipal();
        // 获取数据库中的数据
        LoginInfo loginInfo = loginInfoService.checkUsername(username);

        // 判断令牌的用户名是否存在
        if (loginInfo != null){
            //返回认证信息的时候需要把盐也一并的传过去.
            return new SimpleAuthenticationInfo(loginInfo, loginInfo.getPassword(), getName());
        }
        // 不存在返回null
        return null;
    }
}
